package com.xxx.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xxx.lease.model.entity.BrowsingHistory;
import com.xxx.lease.web.app.mapper.BrowsingHistoryMapper;
import com.xxx.lease.web.app.service.BrowsingHistoryService;
import com.xxx.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
@Slf4j
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {
    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;


    @Override
    @Async  //该注解会开启一个新线程来执行该方法
    public void saveHistory(Long userId , Long id) {

        BrowsingHistory browsingHistory = new BrowsingHistory();
        browsingHistory.setUserId(userId);
        browsingHistory.setRoomId(id);
        browsingHistory.setBrowseTime(new Date());

        //查询登录的用户之前有没有浏览过该房间
        Long count = browsingHistoryMapper.selectCount(new LambdaQueryWrapper<BrowsingHistory>().eq(BrowsingHistory::getUserId, userId).eq(BrowsingHistory::getRoomId, id));
        if(count > 0){
            //更新浏览时间
            browsingHistoryMapper.update(browsingHistory,new LambdaUpdateWrapper<BrowsingHistory>().eq(BrowsingHistory::getUserId, userId).eq(BrowsingHistory::getRoomId, id));
        }else {
            //添加浏览记录
        }
        browsingHistoryMapper.insert(browsingHistory);
    }

    @Override
    public IPage<HistoryItemVo> pageItem(Page<HistoryItemVo> historyItemVoPage, Long userId) {

       return browsingHistoryMapper.pageItem(historyItemVoPage,userId);


    }


}




